export function clone(obj) {
    let str, newobj = obj.constructor === Array ? [] : {}
    if(typeof obj !== 'object'){
        return;
    }else if(window.JSON){
        str = JSON.stringify(obj), //序列化对象
            newobj = JSON.parse(str) //还原
    }else{
        for(var i in obj){
            newobj[i] = typeof obj[i] === 'object' ? clone(obj[i]) : obj[i]
        }
    }
    return newobj;
}
export function is_const(s) {
    let reg = /^[0-9]+.?[0-9]*$/
    if (reg.test(s)) {
        return true;
    }
    if(/^\'|\"\w+\'|\"$/.test(s)){
        return true;
    }
    if(s == "true" || s == "false"){
        return true;
    }
    return false;
}

export function is_number (s) {
    let reg = /^[\-\+]?[0-9]+$/
    return reg.test(s.replace(/\s/g, ''))
}

export function format (s) {
    return s.replace(/\"|\'/g, '\\\"').replace(/\s+/g, '')
}

export function is_data (par, okay) {
    return (new Function('okay','try{\nreturn okay.data.' + par + ' != undefined\n}catch(e){\nreturn false\n}'))(okay)
}
export function is_action (par, okay) {
    return (new Function('okay','try{\nreturn okay.actions.' + par + ' != undefined\n}catch(e){\nreturn false\n}'))(okay)
}
export function is_object (data) {
    return typeof(data) == 'object' && Object.prototype.toString.call(data).toLowerCase() == '[object object]' && !data.length
}
export function is_array (data) {
    return typeof(data) == 'object' && Object.prototype.toString.call(data).toLowerCase() == '[object array]'
}

export function serialize (obj, json = false) {
    if (json) {
        return JSON.stringify(obj)
    }
    let ret = ''
    Object.keys(obj).forEach((name) =>{
        let value = obj[name]
        if (typeof value == 'object') {
            Object.keys(value).forEach((sub) => {
                let subV = value[sub]
                let subName = name + '[' + sub + ']'
                let subObj = {}
                subObj[subName] = subV
                ret += serialize(subObj) + '&'
            })
        }else if (value){
            ret += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&'
        }
    })
    return ret.length?ret.substr(0, ret.length - 1):ret
}

/**
 * 异步任务函数
 */
export function run (taskDef) {
    let task = taskDef()
    let result = task.next();
    (function step() {
       if (!result.done) {
           let promise = Promise.resolve(result.value)
           promise.then(value => {
               result = task.next(value)
               step()
           }).catch(error => {
               throw result = task.throw(error)
               step()
           })
       }else {
           return result.value
       }
    }())
}